package com.example.shengyin.controller;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.entity.Admin;
import com.example.shengyin.entity.Article;
import com.example.shengyin.entity.Job;
import com.example.shengyin.entity.Page;
import com.example.shengyin.service.ArticleService;
import com.example.shengyin.service.JobService;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpRequest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.*;


@RestController
@RequestMapping("/article")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
//swagger
@Api("article表管理")
//redis缓存用
public class ArticleController
{
    @Autowired
    private ArticleService service;
    @Autowired
    private RedisTemplate redisTemplate;
    public Map ReMap(){
        Map<String,List<String>> map=new HashMap<>();
        map.put("公司简介",new ArrayList<>(Arrays.asList("公司简介")));
        map.put("媒体报道",new ArrayList<>(Arrays.asList("媒体报道")));
        map.put("交流合作",new ArrayList<>(Arrays.asList("交流合作")));
        map.put("大事记",new ArrayList<>(Arrays.asList("大事记")));
        map.put("公司新闻",new ArrayList<>(Arrays.asList("开业活动","国际交流","员工活动","亲子活动","公益讲座","公益活动","家长培训","社会关注","全部")));
        map.put("活动讲座",new ArrayList<>(Arrays.asList("热门推荐","专题精选","门店信息")));
        map.put("言语科普",new ArrayList<>(Arrays.asList("言语科普")));
        map.put("课程介绍",new ArrayList<>(Arrays.asList("课程介绍")));
        return map;
    }



    @ApiOperation("分页查询")
    @GetMapping("/list")
    public Result list(Page page, @ApiParam(name = "type",value = "分类") @RequestParam(required = false) String type,
                       @ApiParam(name = "typecode",value = "分类编码") @RequestParam(required = false) String typecode,
                       @ApiParam(name = "createby",value = "创建人") @RequestParam(required = false) String createby,
                       @ApiParam(name = "starttime",value = "类别创建时间的起始值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required =
                               false) Date starttime,
                       @ApiParam(name = "endtime",value = "类别创建时间的结束值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required =
                               false) Date endtime)
    {
        Timestamp start=StrUtil.toTimestamp(starttime);
        Timestamp end=StrUtil.toTimestamp(endtime);
        System.out.println("page:"+page);
        List<Article> list = service.articleList(page,type,typecode,createby,start,end);
        int count = service.countTotall(type,typecode,createby,start,end);
        if(count==0||list==null)
            return Result.error(null);
        page.setData(list);
        page.setCount(count);
        System.out.println(JSON.toJSONString(Result.success(page)));
        return Result.success(page);
    }
    @ApiOperation("单个查找")
    @GetMapping(value = "/select/{id}")
    public Result select(@PathVariable(value = "id") Long id)
    {
        Article article = service.selectById(id);
        article.setVisittimes(article.getVisittimes()+1);
        service.update(article);
        System.out.println(JSON.toJSONString(article));
        if(article==null)
            return Result.error("没有找到数据");
        return Result.success(article);
    }
    @ApiOperation("单个查找NAME")
    @GetMapping(value = "/selectname/{name}")
    public Result select2(@PathVariable(value = "name") String name)
    {
        String type=null;
        String typecode=null;
        List<Article> article = service.selectByNmae(name,type,typecode);
        System.out.println(JSON.toJSONString(article));
        if(article==null)
            return Result.error("没有找到数据");
        return Result.success(article);
    }
    @ApiOperation("添加文章内容")
    @PostMapping("/add")
    public Result insert(@Valid Article article, BindingResult bindingResult, HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        System.out.println("out"+JSON.toJSONString(article));
        article.setCreateby(admin.getRealname());
        int insert = service.insert(article);
        if(insert==0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }
    @ApiOperation("更新")
    @PostMapping("/edit")
    public Result edit(@Valid Article article,BindingResult bindingResult,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        System.out.println("out"+JSON.toJSONString(article));
        if(!(admin.getRoles()==1 || admin.getRealname().equals(article.getCreateby())))
            return  Result.error("您的权限不足或不是该文章的创建者");
        article.setUpdateby(admin.getRealname());
        article.setUpdatetime(new Date());
        System.out.println("<<<<<<<"+JSON.toJSONString(article));
        int insert = service.update(article);
        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }
    @ApiOperation("删除单个")
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id")int id,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        Article article = service.selectById(Long.valueOf(id));
        if(!(admin.getRoles()==1 || admin.getRealname().equals(article.getCreateby())))
            return  Result.error("您的权限不足或不是该文章的创建者");
        int delete = service.deleteById(id);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }
    @ApiOperation("删除多个")
    @GetMapping("/deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable(value = "ids")String ids,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return  Result.error("您的权限不足");
        }
        String s = StrUtil.ListtoString(ids);
        int delete = service.deleteByIds(s);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }



    @ApiOperation("显示")
    @GetMapping("/isvalue/{id}/{isvalue}")
    public Result edit(@PathVariable(value = "id") Long id,
                       @PathVariable(value = "isvalue")boolean isvalue,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        Article article=new Article();
        article.setId(id);
        article.setIsvalid(isvalue);
        article.setShoworder(-1);
        if(!(admin.getRoles()==1))
            return  Result.error("您的权限不足或不是该文章的创建者");
        article.setUpdateby(admin.getRealname());
        article.setUpdatetime(new Date());
        int insert = service.update(article);
        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }
    @ApiOperation("置顶")
    @GetMapping("/showorder/{id}/{showorder}")
    public Result showorder(@PathVariable(value = "id") Long id,
                       @PathVariable(value = "showorder")boolean showorder,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        Article article=new Article();
        article.setId(id);
        if(showorder==true)
            article.setShoworder(1);
        else article.setShoworder(0);
        Article article1 = service.selectById(id);
        article.setIsvalid(article1.isIsvalid());
        if(!(admin.getRoles()==1))
            return  Result.error("您的权限不足或不是该文章的创建者");
        article.setUpdateby(admin.getRealname());
        article.setUpdatetime(new Date());
        int insert = service.update(article);
        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }
}
